package cn.itcast.documentapis;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Date;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * @Description TODO : 批量API允许在单个请求中索引和删除多个文档
 * @Author: zj
 * @Date: 14:11 2019/3/8
 * @Version 1.0
 **/
public class BulkAPI {

    @Test
    public void bulkApi() throws IOException {
        TransportClient client = esClient.getClient();
        //整合多条方法 批量操作
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        bulkRequestBuilder.add(client.prepareIndex("twitter", "_doc", "3")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                        .endObject()
                )
        );

        bulkRequestBuilder.add(client.prepareIndex("twitter", "_doc", "5")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "another post")
                        .endObject()
                )
        );
        //删除操作
        bulkRequestBuilder.add(client.prepareDelete("twitter", "_doc", "3").request());
        BulkResponse bulkItemResponses = bulkRequestBuilder.get();
        if (bulkItemResponses.hasFailures()) {

        }
    }
}
